/** file Audio.cpp
    author belot.nicolas
*/

#include "Audio.h"
#include <iostream>
namespace libtrckr {
double *Audio::sbuffer=0;
bool *Audio::lock = (bool*)malloc(sizeof(bool));
int *Audio::start = (int*)malloc(sizeof(int));
int *Audio::end = (int*)malloc(sizeof(int));
int *Audio::size = (int*)malloc(sizeof(int));
int *Audio::capacity = (int*)malloc(sizeof(int));
Audio::~Audio(){

}

void Audio::channels(int chan){
	_channels=chan;
}

int Audio::channels() const{
	return _channels;
}

void Audio::bitrate(int br){
	_bitrate=br;
}

int Audio::bitrate() const {
	return _bitrate;
}

int Audio::getFrames(int frames,double *data){
	if(sbuffer!=NULL && *size >= (channels()*frames) ){
		int element=*start;
		for(uint i=0;i<frames;i++){
			for(uint j=0;j<channels();j++){
				element=(*start)+i*channels()+j;
				if(element>=(*capacity)) element-=(*capacity);
				data[i*channels()+j]=sbuffer[element];
			}
		}
	//	std::cout << "last element " << element << std::endl;
		*start=element;
		*size-= frames*channels();
		return frames;
	}else{
		return 0;
	}
}

void Audio::copy(Buffer& src){
	int element=*end;
	src.setChannel(0);
	while(src.hasNextChannel()){
		for(uint i=0;i<src.size();i++){
			element=(*end)+(i*src.channels())+src.getChannel();
			if(element>=(*capacity)) element-=(*capacity);
				sbuffer[element]=src[i];
		}
		src.nextChannel();
	}
	*end=element;
	*size+=src.size()*src.channels();
}

void Audio::copy(double *data, int msize){
	int element;
	for(uint i=0;i<msize;i++){
		element=(*end)+i;
		if(element>=(*capacity)) element-=(*capacity);
				sbuffer[element]=data[i];
	}
	*end=element;
	*size+=msize;
}

}


